//app.js  "navigationStyle": "custom"
var com = require("./utils/common.js");
var util = require("./utils/util.js");
const DEBUG = false; //开启调试模式  不会判定上次进入的端。每次提交版本更改为false
App({
  onLaunch: function () {
    try {
      false
      this.globalData.systemInfo = wx.getSystemInfoSync();
    } catch (error) {
      console.log("get systemInfo fail", error);
    }
    var that = this;
    // 展示本地存储能力
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        //console.log(wx.getStorageSync('token'));
        //if (!wx.getStorageSync('token')) {
        // this.getOpenid(res.code);
        //}
      }
    });
    this.login();
    //获取用户信息
    // wx.getSetting({
    //   success(res) {
    //     if (!res.authSetting['scope.userInfo']) {
    //       wx.authorize({
    //         scope: 'scope.userInfo',
    //         success() {

    //         }
    //       })
    //     } else {

    //     }

    //   }
    // })



    if (DEBUG == false) {
      const loginType = wx.getStorageSync('role'); //角色 1维修人员  2销售 3合伙人
      console.log(loginType, "loginType")
      if (loginType) {
        let navigate;
        if (loginType == 1) {
          navigate = "/engineering/pages/index/index";
        } else if (loginType == 2) {
          navigate = "/promoter/pages/index/index";
        } else if (loginType == 3) {
          navigate = "/pages/partner/index/index";
          wx.switchTab({
            url: navigate,
          })
          return false;
        }
        wx.reLaunch({
          url: navigate
        })
      }
    }




  },
  onShow() {

    //wx.removeStorageSync('token')
    wx.removeStorageSync('session_key');
    wx.removeStorageSync('nickName');
  },

  login() {
    wx.login({
      success: res => {
        //  发送 res.code 到后台换取 openId, sessionKey, unionId
        //console.log(wx.getStorageSync('token'));
        if (!wx.getStorageSync('token')) {
          this.getOpenid(res.code); //暂时不需要
        }
      }
    });
  },
  //发起网络请求,获取openid,session_key
  getOpenid: function (code) {
    var that = this;
    that.ajax({
      url: 'Common/Wx/getUserOpenid',
      method: "POST",
      data: {
        code: code
      },
      success: function (res) {
        if (res.data.code == 1000) {
          wx.setStorageSync('openid', res.data.data.openid);
          wx.setStorageSync('session_key', res.data.data.session_key);
        }
      }
    })
  },

  //弹窗MODEL
  showModal(title = "提示", content = "", success = function () {}) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          success();
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },
  //查询版本
  compareVersion(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)
      
        while (v1.length < len) {
          v1.push('0')
        }
        while (v2.length < len) {
          v2.push('0')
        }
      
        for (let i = 0; i < len; i++) {
          const num1 = parseInt(v1[i])
          const num2 = parseInt(v2[i])
      
          if (num1 > num2) {
            return 1
          } else if (num1 < num2) {
            return -1
          }
        }
      
        return 0
  },
  //扫描设备二维码
  scanDeviceCode(onlyFromCamera = false) {
    return new Promise((resolve, reject) => {
      wx.scanCode({
        onlyFromCamera,
        success: res => {
          const result = res.result;
          let code = "";
          if (~result.indexOf("=")) {
            let arr = result.split("=");
            if (arr.length == 2 && arr[1]) {
              code = arr[1];
            } else {
              reject("请扫描正确的二维码")
            }
          } else {
            code = result;
          }
          resolve(code)
        },
        fail: e => {
          reject("扫码失败，请重试")
        }
      })
    })
  },

  //ajax 请求
  ajax(model) {
    var that = this;
    if (util.isExitsVariable(model.load)) {
      var msg = '加载中';
      if (util.isExitsVariable(model.msg)) {
        var msg = model.msg;
        wx.showLoading({
          title: msg,
        })
      }
    }
    if (!util.isExitsVariable(model.method)) {
      model.method = "POST";
    }
    // 判断请求哪个接口
    if (model.url_type == 1) {
      //拼接url model.url_type == 1  仅代表Boss后台请求
      if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = this.globalData.boss_url + model.url;
      }
    } else {
      //拼接url
      if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = this.globalData._url + model.url;

      }
    }

    //get参数拼接
    if (model.method == "get" && model.data !== undefined) {
      for (let k in model.data) {
        if (model.data[k].toString() !== '') {
          model.url = model.url + "&" + k + "=" + model.data[k];
        }
      }
      model.data = '';
    }
    //返回Promise对象
    return new Promise(
      function (resolve) {
        var token = wx.getStorageSync('token');
        // console.log(">>>>>>>",token);
        wx.request({
          method: model.method,
          url: model.url,
          header: {
            "Company-No": that.globalData.company_no,
            'token': token // 默认值
          },
          data: model.data,
          success: (resolve) => {
            if (util.isExitsVariable(model.load)) {
              wx.hideLoading();
            }
            if (resolve.data.code == -1004) {
              that.showToast('请登录~');
              setTimeout(function () {
                wx.reLaunch({
                  url: '/pages/login/login',
                })
              }, 500);
              return false;
            }
            model.success(resolve);

          },
          error: (e) => {
            console.log(e, "error")
            model.error(resolve);
          }
        })
      }
    )
  },
  globalData: {
    systemInfo: {},
    userInfo: null,
    _network_path:'https://qiniu.youheone.cn/manage_weapp/',
    company_no:20001,//公司编号,提交版本时注意确认
    /**正式环境 */
    _url: 'https://water.youheone.com/',
    boss_url: 'https://boss.youheone.com/',
    //wxc3f5aa4ce7d6f70e
    /***测试环境 */
    // _url: 'https://waterapi.wechat-app.me/',
    // boss_url: 'https://test.cqthesis.cn/',
    //wx09e9933bf660cc87
    //_url: 'https://waterapi.wechat-app.me/',
    //boss_url: 'https://test.cqthesis.cn/',
  },
  //弹窗toast
  showToast(title = "网络错误~", icon = "none", duration = 2000, complete = function () {}) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration,
      complete: function (res) {
        complete();
      }
    })
    return false;
  },


  formatCard(str) {
    return str.replace(/\s/g, '').replace(/(\d{4})(?=\d)/g, "$1 ")
  },

  //清除所有个空格
  trimAll(str) {
    return str.replace(/\s*/g, '');
  },

  //保留两位小数
  retainDecimal(value) {
    return value === "" ? "" : value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
  },


  //浮点数相加
  add(a, b) {
    var c, d, e;
    try {
      c = a.toString().split(".")[1].length;
    } catch (f) {
      c = 0;
    }
    try {
      d = b.toString().split(".")[1].length;
    } catch (f) {
      d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e;
  },

  //浮点数相减
  sub(a, b) {
    var c, d, e;
    try {
      c = a.toString().split(".")[1].length;
    } catch (f) {
      c = 0;
    }
    try {
      d = b.toString().split(".")[1].length;
    } catch (f) {
      d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e;
  },

  //浮点数相乘
  mul(a, b) {
    var c = 0,
      d = a.toString(),
      e = b.toString();
    try {
      c += d.split(".")[1].length;
    } catch (f) {}
    try {
      c += e.split(".")[1].length;
    } catch (f) {}
    return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
  },

  //浮点数相除
  div(a, b) {
    var c, d, e = 0,
      f = 0;
    try {
      e = a.toString().split(".")[1].length;
    } catch (g) {}
    try {
      f = b.toString().split(".")[1].length;
    } catch (g) {}
    return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e));
  }
})